<script setup>
import { nextTick, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { pcaTextArr } from "element-china-area-data";
import { Message } from "@arco-design/web-vue";
import schoolApi from "@/api/schoolApi";
import Upload from "@/components/Upload.vue";
const router = useRouter();

const schoolForm = ref();
const searchForm = ref();
const searchModel = reactive({});
const visible = ref(false);
const optionVisible = ref(false);
const importVisable = ref(false);
let schoolData = ref({});
let optionData = ref({});
const loading = ref(false);
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search();
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search();
  },
});

let uploadErrorList = ref([]);

const columns = [
  {
    title: "学校名称",
    dataIndex: "name",
  },
  {
    title: "学校类别",
    dataIndex: "schoolTypeText",
  },
  {
    title: "所属地区",
    dataIndex: "citys",
  },
  {
    title: "班级数量",
    dataIndex: "classesNum",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const rowSelection = ref({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});

const selectedKeys = ref([]);

const data = ref([]);

const showAddDialog = () => {
  visible.value = true;
  schoolForm.value.resetFields();
  schoolData.value = {}
};

const editRecord = (record) => {
  visible.value = true;
  nextTick(() => {
    schoolForm.value.resetFields();
    schoolData.value = Object.assign({}, record);
    schoolData.value.citys = record.citys;
  });
};

const deleteRecord = (record) => {
  schoolApi.delete({
    id: record.id
  }).then(res => {
    search();
  })
};

const showPasswordOption = (record, isBatch) => {
  optionVisible.value = true;
  if (!isBatch) {
    optionData.value.id = record.id;
    optionData.value.password = "";
  } else {
    optionData.value.schoolIds = selectedKeys.value;
    optionData.value.password = "";
  }
}

const clearStudent = () => {
  if (optionData.value.schoolIds && optionData.value.schoolIds.length > 0) {
    schoolApi.batchClearStudent(optionData.value).then(res => {
      search();
      optionVisible.value = false;
      selectedKeys.value = [];
    })
  } else {
    schoolApi.clearStudent(optionData.value).then(res => {
      search();
      optionVisible.value = false;
    })
  }
}

const managerSchool = (record) => {
  let params = {
    schoolId: record.id,
  };
  router.push({
    name: "schoolManager",
    state: {
      params,
    },
  });
};

const handleSubmitSuccess = (values, e) => {
  let me = this;
  values.province = values.citys[0];
  values.city = values.citys[1];
  values.area = values.citys[2];
  values.schoolType = values.schoolTypes.toString();
  schoolApi.save(values).then((res) => {
    visible.value = false;
    Message.success("保存成功");
    search();
  });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  schoolApi.schoolPage(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const reset = () => {
  searchForm.value.resetFields();
};

const showImportDialog = () => {
  importVisable.value = true;
  uploadErrorList.value = [];
}

const closeUploadDialog = () => {
  importVisable.value = false;
  search();
};

search();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>学校管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="name" label="学校名称">
                  <a-input v-model="searchModel.name" placeholder="请输入学校名称" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="schoolType" label="学校类别">
                  <a-select v-model="searchModel.schoolType" placeholder="请选择学校类别">
                    <a-option value="1">小学</a-option>
                    <a-option value="2">初中</a-option>
                    <a-option value="3">高中</a-option>
                    <a-option value="4">大学</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search(1, 15)">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">

              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <a-card style="margin-top: 20px">
      <div class="toolbar">
        <a-space>
          <a-button type="primary" size="small" @click="showAddDialog">

            <template #icon>
              <icon-plus />
            </template>
            新增学校
          </a-button>
          <a-button type="outline" size="small" @click="showImportDialog">
            <template #icon>
              <icon-upload />
            </template>
            导入学校
          </a-button>
          <a-popconfirm content="该操作会删除学校所有学生和班级数据，确认操作吗？" @ok="showPasswordOption([], true)">
            <a-button :disabled="selectedKeys.length == 0" size="small" type="primary" status="danger">
              <template #icon>
                <icon-delete></icon-delete>
              </template>
              批量清空学生</a-button>
          </a-popconfirm>
        </a-space>
      </div>
      <a-table :columns="columns" row-key="id" v-model:selectedKeys="selectedKeys" :row-selection="rowSelection"
        :loading="loading" :data="data" @page-change="pagination.pageChange"
        @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">

        <template #action="{ record }">
          <a-space>
            <a-button type="primary" size="mini" @click="editRecord(record)">编辑</a-button>
            <a-popconfirm content="该操作会删除学校所有学生和班级数据，确认操作吗？" @ok="deleteRecord(record)">
              <a-button type="primary" size="mini" status="danger">删除</a-button>
            </a-popconfirm>
            <a-popconfirm content="该操作会删除学校所有学生和班级数据，确认操作吗？" @ok="showPasswordOption(record, false)">
              <a-button type="primary" size="mini" status="danger">清空学生</a-button>
            </a-popconfirm>
            <!-- <a-button type="text" @click="managerSchool(record)">管理</a-button> -->
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
  <a-modal v-model:visible="visible" width="700px" title="新增学校" :footer="null">
    <a-form ref="schoolForm" size="large" :model="schoolData" @submit-success="handleSubmitSuccess">
      <a-form-item field="name" label="学校名称" :rules="[{ required: true, message: '请输入学校名称' }]">
        <a-input v-model="schoolData.name" placeholder="请输入学校名称" />
      </a-form-item>
      <a-form-item field="schoolTypes" label="学校类别" :rules="[
        {
          type: 'array',
          minLength: 1,
          required: true,
          message: '请选择学校类别',
        },
      ]">
        <a-checkbox-group :disabled="schoolData.id && schoolData.id.toString().length > 0"
          v-model="schoolData.schoolTypes">
          <a-checkbox value="1">小学</a-checkbox>
          <a-checkbox value="2">初中</a-checkbox>
          <a-checkbox value="3">高中</a-checkbox>
          <a-checkbox value="4">大学</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item field="citys" label="所属地区" :rules="[
        {
          type: 'array',
          minLength: 3,
          required: true,
          message: '请选择所属地区',
        },
      ]">
        <a-cascader v-model="schoolData.citys" :path-mode="true" expand-trigger="hover" :options="pcaTextArr"
          placeholder="请选择所属地区" />
      </a-form-item>
      <a-form-item field="code" label="学校编码">
        <a-input v-model="schoolData.code" placeholder="请输入学校编码" />
      </a-form-item>
      <a-form-item field="address" label="详细地址">
        <a-textarea v-model="schoolData.address" placeholder="请输入详细地址" />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button html-type="submit" type="primary">保存</a-button>
          <a-button @click="() => {
            visible = false;
          }
          ">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="importVisable" width="600px" :hide-cancel="true" @ok="closeUploadDialog" :draggable="true"
    title="导入学校数据">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        <div>本平台为互联网非涉密平台，严禁处理、传输国家秘密、工作秘密及敏感信息。请确认扫描、传输的文件资料不涉及上述信息。</div>
        <div>暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传</div>
      </div>
      <a-button type="link" href="/学校导入模板.xlsx" style="margin-bottom: 10px">学校导入模板下载</a-button>
      <Upload accept=".xls,.xlsx" v-model:uploadErrorList="uploadErrorList" :draggable="true"
        action="/admin/v1/school/import" />
      <div class="upload-error-con" v-if="uploadErrorList && uploadErrorList.length > 0">
        <div class="title">错误信息：</div>
        <div class="upload-error-item" v-for="error in uploadErrorList" :key="error">
          {{ error }}
        </div>
      </div>
    </a-space>
  </a-modal>

  <a-modal v-model:visible="optionVisible" title="清空所有学生数据" :footer="null">
    <a-form ref="optionForm" size="large" :model="optionData" @submit-success="clearStudent">
      <a-form-item field="password" label="账号密码" :rules="[{ required: true, message: '请输入账号密码' }]">
        <a-input type="password" v-model.trim="optionData.password" placeholder="请输入账号密码" />
      </a-form-item>
      <a-form-item>
        <div style="color: red; font-size: 12px">
          注：请谨慎操作，将会清空该学校所有学生数据！
        </div>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">确认</a-button>
          <a-button @click="optionVisible = false">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.logo {
  font-size: 18px;
  text-align: center;
  color: #1c1f23;
  /* padding: 12px; */
  height: 55px;
  line-height: 55px;
  font-family: Inter, -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC,
    Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial,
    sans-serif;
  font-weight: 600;
}

.bg-base {
  background-color: rgba(243, 243, 245, 1);
}
</style>
